import React, { Component } from "react";
import PropTypes from "prop-types";

import {
  View,
  Text,
  PanResponder,
  StyleSheet,
  Image,
  Dimensions,
} from "react-native";

import Color from "../../config/theme/standard/color";
import fontSize from "../../config/theme/standard/fonts";
class ScaleSlider extends Component {

  // eslint-disable react/no-unused-prop-types
  constructor(props) {
    super(props);
    //定义 系统变量
    this.state = {
      stepLayLeft: 0,
      lenArr: [],
      lineArr: [],
      list: [],
      min: 0,
      unitAmount: 0,
      unitWidth: 0,
    };
    //初始化定义变量
    this.oldTouchLeft = "";
    this.newTouchLeft = "";
    this.defaultCount = "";
    this.idx = 1;
    this.stepwidth = "";
    this.timer = null;
  }

  componentWillMount() {
    // 增加监听器,监听触摸事件
    this._panResponeder = PanResponder.create({
      onStartShouldSetPanResponder: (e, gestureState) => true,
      onMoveShouldSetPanResponder: (e, gestureState) => true,
      onPanResponderStart: this.eventStart.bind(this),
      onPanResponderMove: this.eventMove.bind(this),
      onPanResponderEnd: this.eventEnd.bind(this),
    });
  }

  componentDidMount() {
    // 初始化刻度尺
    
    // 动态设置left 值
    this.setState({
      stepLayLeft: this.setPoslf(this.props.defaultValue),
    });
    // 监听屏幕宽度变化
    this.dimensionsListener = Dimensions.addEventListener("change", () => {
      // 适配折叠屏重新计算卡尺left
      this.forceUpdate();
     
      this.timer = setTimeout(()=> {
        const stepLayLeft = this.setPoslf(this.props.defaultValue)
        this.setState({
          stepLayLeft: stepLayLeft,
        });
      })
                                                            
    });
	this.inintDraw(this.props);
  }
  componentWillUnmount() {
    // 移除监听
    this.dimensionsListener && this.dimensionsListener.remove();
    if (this.timer) {
      clearTimeout(this.timer)
      this.timer = null
    }
  }

  // 根据当前数组动态计算卡尺left
  setPoslf(value) {
    
    const { min, unitAmount, unitWidth } = this.props;
    const left = ((value - min) * unitWidth) / unitAmount - this.stepwidth / 2;

    return -left;
  }

  // 触摸事件结束
  eventEnd(e, gestureState) {
    if (gestureState.moveX == 0) return;
    const { min, unitAmount, unitWidth, unitStep, list } = this.state;
    const { endBack, sliderList, forMat } = this.props;

    this.oldTouchLeft = this.correctNum(
      this.oldTouchLeft,
      unitAmount,
      unitStep
    );

    let pageX =
      ((min - this.oldTouchLeft) * unitWidth) / unitAmount + this.stepwidth / 2;

    this.setState({
      stepLayLeft: pageX,
      value: this.oldTouchLeft,
    });

    this.stepTouch.setNativeProps({
      style: {
        left: pageX,
      },
    });
    // 传入自定义数组 通过该判断 返回数组内容
    if (sliderList.length && endBack) {
      // 找到对应的项的下标
      let sliderIndex = sliderList.findIndex((item) => {
        return item.value === this.oldTouchLeft;
      });
      // 回传给父组件
      endBack({ value: sliderList[sliderIndex].name });
      return;
    }

    if (endBack) {
      let value = "";
      switch (forMat) {
        case "%":
          value =
            this.oldTouchLeft == "0"
              ? this.oldTouchLeft
              : this.oldTouchLeft + forMat;
          break;
        case "":
          value = this.oldTouchLeft;
          break;
        default:
          value = forMat + this.oldTouchLeft;
          break;
      }
      // debugger
      endBack({ value });
    }
  }

  move(e, gestureState) {

    const { min, touchMin, touchMax, unitAmount, unitWidth } = this.state;

    let pageX = gestureState.dx + this.left;

    let onValue =
      min + -((pageX - this.stepwidth / 2) * unitAmount) / unitWidth;
    // 最值校准
    if (onValue <= touchMin) {
      onValue = touchMin;
      pageX = this.setPoslf(touchMin);
    } else if (onValue >= touchMax) {
      onValue = touchMax;
      pageX = this.setPoslf(touchMax);
    }
    // 保存新值 方便停止回校
    this.oldTouchLeft = onValue;

    this.stepTouch.setNativeProps({
      style: {
        left: pageX,
      },
    });

    this.newTouchLeft = pageX;

  }

  eventMove(e, gestureState) {
    this.move(e, gestureState);
    return true;
  }
  //  触摸开始  记录位置
  eventStart(e, gestureState) {
    // 存值 进行比对
    if (this.left) {
      this.left = this.newTouchLeft;
    } else {
      this.left = this.state.stepLayLeft;
    }
    this.props.moveStart && this.props.moveStart();
    return true;
  }

  // 不允许其他视图劫持 该组件
  giveUpEvent(e) {
    return false;
  }
  // 初始化刻度尺
  inintDraw(props) {
    const {
      unitAmount,
      unitWidth,
      defaultValue,
      min,
      max,
      touchMin,
      touchMax,
      fontSize,
      fontColor,
      longScaleColor,
      shortScaleColor,
      width,
      unitStep,
      sliderList,
      forMat,
      height,
      itemMargin,
      oddEven,
      source,
      longScaleLength,
      shortScaleLength,
      isShowZero,
      itemStyle,
    } = props;

    // 根据最值生成相应刻度
    let list = [];
    let name = "";
    for (let i = min; i <= max; ) {
      name = String(forMat == "%" ? i && i + forMat : forMat + i);
      list.push({
        name,
        value: i,
      });

      i += unitAmount * unitStep;
    }
    if (sliderList.length) {
      list = sliderList;
    }
    const len = list.length;
    const lenArr = Array(len).fill(0);
    const lineArr = Array(Math.ceil((max - min) / unitAmount) + 1).fill(0);
    this.setState({
      list,
      lenArr,
      lineArr,
      defaultValue,
      touchMin: touchMin !== undefined ? touchMin : min,
      touchMax: touchMax !== undefined ? touchMax : max,
      value: defaultValue,
      unitAmount,
      unitWidth,
      min,
      fontSize,
      fontColor,
      longScaleColor,
      shortScaleColor,
      width,
      height,
      itemMargin,
      oddEven,
      source,
      shortScaleLength,
      longScaleLength,
      isShowZero,
      itemStyle,
      unitStep,
    });
  }
  // 定义一个函数 用来校对刻度值
  correctNum(num, unitAmount, unitStep) {
    num = Math.round(Number(num));
    let stande = unitAmount * unitStep;

    let remainder = num % stande;
    if (remainder == 0) {
      return num;
    }
    // 50%比例吸附
    if (remainder < stande / 2) {
      return (num = num - remainder);
    }
    if (remainder >= stande / 2) {
      return (num = num + stande - remainder);
    }
  }

  // 回显标识
  isFlag(index, itemMargin, oddEven, value) {
    let flag;
    let isShowZero = this.state.isShowZero;
    switch (oddEven) {
      case "odd":
        flag = index == 0 || index % 2 !== 0;
        break;
      case "even":
        flag = index == 0 || index % 2 == 0;
        break;
      default:
        if (index == 0 || this.defaultCount == index) {
          this.idx++;
          this.defaultCount = (this.idx - 1) * (itemMargin + 1);
          flag = true;
        } else {
          flag = false;
        }
        break;
    }

    flag = flag && this.setLine(value, 1);

    if (value == 0) flag = isShowZero;

    return flag;
  }

  // 样式渐变调整
  /***
   * pol：当前所对应的刻度值
   * type：0, 刻度线的渐变 1 刻度值的回显
   */
  setLine(pol, type) {
    let { touchMin, touchMax } = this.state;

    if (touchMin > pol || touchMax < pol) {
      return type == 0 ? 0.1 : false;
    }
    return type == 0 ? 1 : true;
  }

  render() {
    const {
      list,
      lenArr,
      lineArr,
      min,
      unitAmount,
      unitWidth,
      stepLayLeft,
      fontSize,
      fontColor,
      shortScaleColor,
      longScaleColor,
      width,
      height,
      itemMargin,
      oddEven,
      source,
      longScaleLength,
      shortScaleLength,
      itemStyle,
    } = this.state;

    if (this.defaultCount) {
      this.defaultCount = "";
      this.idx = 1;
    }
    // 获取 移动端窗口宽度
    if (typeof this.props.width == "string") {
      this.stepwidth = Dimensions.get("window").width - 15 - 1;
    } else {
      this.stepwidth = this.props.width - 15 - 1;
    }
    // 小刻度线的结构
    let lineHTML = lineArr.map((re, idx) => {
      return (
        <View
          key={idx}
          style={[
            {
              backgroundColor: shortScaleColor,
              height: shortScaleLength,
              left: unitWidth * idx,
              opacity: this.setLine(idx * unitAmount + min, 0),
            },
            styles.line,
          ]}
        ></View>
      );
    });

    // 大刻度线和刻度值的结构
    let nameHTML = lenArr.map((re, index) => {
      // 定义刻度值结构
      let itemHTML = null;

			// 处理假报错防止项目崩溃
			if (list.length && list[index] && list[index].name) {

				itemHTML = <Text style={{ position: 'absolute', zIndex: 1, top: longScaleLength+6, left: -(list[index].name.length+1) * fontSize / 2, textAlign: "center", width: (list[index].name.length+1) * fontSize, fontSize: fontSize, color: fontColor ,fontWeight:'700'}} >
					{`${list[index].name}`}
				</Text>

			}


			return (
				// 刻度盘结构
				<View key={index}
					style={{ position: "absolute", width: 900, top: 0, left: ((Number(list[index].value) - min) / unitAmount) * unitWidth, zIndex: 1 }}>
					<View style={{ width: 1, height: longScaleLength, backgroundColor: longScaleColor, opacity: this.setLine(list[index].value, 0) }}>
					</View>
					{this.isFlag(index, itemMargin, oddEven, list[index].value) ? itemHTML : null}
				</View>
			)
		})

    // 用来区分是否适配屏幕宽度还是自传
    let type = typeof width == "string" ? 0 : 1;

    let imgLeft =
      type == 1 ? width && width - 15 : this.stepwidth && this.stepwidth - 30;

    return (
      <View
        style={styles.slider}
        {...this._panResponeder.panHandlers}
        onResponderTerminationRequest={(event) => {
          this.giveUpEvent(event);
        }}
      >
        <View style={[styles.stepWrap, { width: width, height: height }]}>
          <View
            style={[styles.stepTouch, { left: stepLayLeft }]}
            ref={(n) => {
              this.stepTouch = n;
            }}
          >
            <View style={styles.stepLine}>
              {lineArr.length > 0 ? lineHTML : null}
            </View>
            <View style={styles.name}>
              {lenArr.length > 0 ? nameHTML : null}
            </View>
          </View>
        </View>
        <View style={[styles.imgWrap, { left: (this.stepwidth + 1) / 2 + 9 }]}>
          <Image
            style={[styles.img, itemStyle]}
            source={source || require("../../assets/scaleSlider_guidingPrinciple.png")}
          ></Image>
        </View>
        <View
          style={[
            styles.mask,
            { height: longScaleLength && longScaleLength + 10, left: -10 },
          ]}
        ></View>
        <View
          style={[
            styles.mask,
            { height: longScaleLength && longScaleLength + 10, left: imgLeft },
          ]}
        ></View>
      </View>
    );
  }
}

// 样式表
const styles = StyleSheet.create({
  slider: {
    position: "relative",
    overflow: "hidden",
    width: "100%",
    padding: 15,
  },
  stepWrap: {
    position: "relative",
    top: 5,
    overflow: "hidden",
  },
  stepTouch: {
    position: "absolute",
    top: 0,
    left: 10,
    width: 1000000,
    height: "100%",
  },
  stepLine: {
    width: 1000000,
    position: "relative",
    left: 0,
    top: 0,
    backgroundColor: "yellow",
  },
  line: {
    position: "absolute",
    width: 1,
    top: 0,
    overflow: "visible",
  },
  stepName: {
    width: 1000000,
    position: "relative",
    left: 0,
    top: 0,
  },
  name: {
    position: "absolute",
    width: 1,
    left: 0,
    top: 0,
  },
  stepTitle: {
    position: "absolute",
    width: 60,
    top: 10,
    height: 24,
    left: -30,
    textAlign: "center",
    color: "#000",
  },
  imgWrap: {
    position: "absolute",
    top: 0,
  },
  img: {
    width: 12,
    height: 32,
    resizeMode: "contain",
  },
  mask: {
    position: "absolute",
    top: 10,
    width: 50,
    backgroundColor: "#fff",
    opacity: 0.8,
  },
});

export default ScaleSlider;

ScaleSlider.propTypes = {
  endBack: PropTypes.func,
  moveStart: PropTypes.func,
  unitAmount: PropTypes.number,
  unitWidth: PropTypes.number,
  touchMin: PropTypes.number,
  touchMax: PropTypes.number,
  min: PropTypes.number,
  max: PropTypes.number,
  fontSize: PropTypes.number,
  fontColor: PropTypes.string,
  longScaleColor: PropTypes.string,
  shortScaleColor: PropTypes.string,
  unitStep: PropTypes.number,
  sliderList: PropTypes.instanceOf(Array),
  forMat: PropTypes.string,
  itemMargin: PropTypes.number,
  oddEven: PropTypes.string,
  defaultValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  shortScaleLength: PropTypes.number,
  longScaleLength: PropTypes.number,
  source: PropTypes.any,
  itemStyle: PropTypes.object,
  isShowZero: PropTypes.bool,
};

ScaleSlider.defaultProps = {
  defaultValue: 0, //设置初始指针值
  endBack() {}, //回调函数
  unitAmount: 20, //每刻度值。
  unitWidth: 12, //每刻度间距
  // touchMin: 0,													//可拖动最小值
  // touchMax: 9900,                    							    //可拖动最大值
  min: 0, //最小值
  max: 10000, //最大值
  fontSize: fontSize.scaleSlider.textFontSize, //字号
  fontColor: Color.scaleSlider.textColor, //文字颜色
  longScaleColor: Color.scaleSlider.long, //长刻度线颜色
  shortScaleColor: Color.scaleSlider.short, //短刻度线颜色
  width: "100%", //刻度尺宽度
  height: 50, //刻度尺高度
  unitStep: 5, //单位份数
  sliderList: [], //自定义数组
  forMat: "", //格式化
  itemMargin: 0, //每一项间隔
  oddEven: "odd", //奇偶回显
  longScaleLength: 12, //长刻度线长度
  shortScaleLength: 6, //短刻度线长度
  isShowZero: true, // 刻度值为零是否显示
};